package cn.xinjiu.reggie.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * Created by xinchen on 2022/7/3
 *
 * @Description : 全局异常处理
 */
// 切面，属性为控制器类型     拦截Controller
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody  // 控制器返回JSON数据
@Slf4j         // 日志打印
public class GlobalExceptionHandler {

    /**
     * @param ex
     * @return
     * @description 异常处理方法，  @ExceptionHandler 注解指定异常类型
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());

        if (ex.getMessage().contains("Duplicate entry")) {
            String[] s = ex.getMessage().split(" ");
            String msg = s[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }


    /**
     * @param ex
     * @return
     * @description 异常处理方法，  @ExceptionHandler 注解指定异常类型
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

}
